package com.demo.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security配置类
 * 配置安全策略，允许登录接口无需认证
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    /**
     * 密码编码器
     * @return BCryptPasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置安全过滤器链
     * @param http HttpSecurity对象
     * @return SecurityFilterChain
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            // 禁用CSRF保护
            .csrf(csrf -> csrf.disable())
            // 禁用默认的HTTP Basic认证
            .httpBasic(httpBasic -> httpBasic.disable())
            // 禁用默认的表单登录
            .formLogin(formLogin -> formLogin.disable())
            // 配置授权规则
            .authorizeHttpRequests(authz -> authz
                // 允许登录接口访问
                .requestMatchers("/user/login").permitAll()
                // 允许健康检查接口访问
                .requestMatchers("/user/health").permitAll()
                // 允许Actuator端点访问
                .requestMatchers("/actuator/**").permitAll()
                // 允许API文档访问
                .requestMatchers("/api/user/**").permitAll()
                // 允许所有请求（临时解决方案）
                .anyRequest().permitAll()
            )
            // 配置会话管理为无状态
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .build();
    }
}